package com.soufang.ui;

import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.zxx.adapter.houseListAdapter;
import com.zxx.common.Common;
import com.zxx.pullRefresh.MyListener;
import com.zxx.pullRefresh.PullToRefreshLayout;
import com.zxx.pullRefresh.PullableListView;
import com.zxx.sql.houseData;
import com.zxx.sql.sqlMan;
import com.zxx.sql.sqlParam;
import com.zxx.threadModule.handleThreadModule;
import com.zxx.view.ExpandTabView;
import com.zxx.view.ViewArea;
import com.zxx.view.ViewMore;
import com.zxx.view.ViewPrice;

/**
 * @brief 点击买新房后的弹出fragment页面
 * @author zxx
 * 
 */
public class newHouseFragment extends Fragment {
	
	private ExpandTabView expandTabView;
	
	private ArrayList<View> mViewArray = new ArrayList<View>();
	private sqlParam msqlParam;//存放数据库相关数据的列表
	private ViewPrice viewPrice;
	private ViewMore viewMore;
	private ViewArea viewArea;	
	private PullableListView houselv;
	private List<houseData> mhouselist;
	private houseListAdapter madapter;
	
	private sqlMan sqlManager;
	private handleThreadModule<View> mHandleSql; 
	
	private enum AREACOUNT{
		ALL,
		GTHY,
		LXXC,
		ZGC,
		JTXC,
		JNSD,
		CXXC,
		XTXQ,
		JZXQ,
		MJXY,
		HFHY;
	}
	
	private enum MORESELECT{
		SORT,
		HOUSETYPE,
		ZX,
		PMPRICE;
	}
	
	private enum SORTKIND{
		SORTALL,
		SORTBYPMPRICEH_L,
		SORTBYPMPRICEL_H,
		SORTBYYEARH_L,
		SORTBYYEARL_H,
		SORTBYAREAH_L,
		SORTBYAREAL_H;
	}
		
	private static final int sortArea = 0;
	private static final int sortTotalPrice = 1;
	private static final int sortMore = 2;
	
	private String mcity;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mcity =  getActivity().getIntent().getStringExtra(Common.KEY_CITY);
	 	
		sqlManager = sqlMan.get(getActivity());
		mHandleSql = new handleThreadModule<View>(new Handler());
		mHandleSql.setListener(new handleThreadModule.Listener<View>() {
				public void onUpdateTextView(List<houseData> list,boolean bcleanAll,sqlParam param)
				{
					//mhouselist = list; //这样不刷新adapter
					if(bcleanAll){
						mhouselist.clear();
						mhouselist.addAll(list);
						
					}else{
						mhouselist.addAll(list);
					}
					msqlParam = param;
					madapter.notifyDataSetChanged();
					
				}
			});
		mHandleSql.start();
		mHandleSql.getLooper();
		
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		mHandleSql.clearQueue();
		mHandleSql.quit();
		onBackPressed();
	}

	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		View v = inflater.inflate(R.layout.fragment_common, container, false);
		
		initView(v);
		initVaule();
		initListener();
		msqlParam = new sqlParam();
		msqlParam.setCmd(Common.MESSAGE_INSERTSQL);
		msqlParam.setMselectIndex(0);
		msqlParam.setMselectnum(Common.MAXSQLDATANUM);
		//第一次查询，没有已经存在的列数
		mHandleSql.SendMsg(Common.MESSAGE_INSERTSQL,0,0,msqlParam);
		
		return v;
	}
	

private void initView(View v) {
		
		expandTabView = (ExpandTabView) v.findViewById(R.id.expandtab_view);
		
		viewPrice = new ViewPrice(getActivity());
		viewMore = new ViewMore(getActivity());
		viewArea = new ViewArea(getActivity());
		
		final PullToRefreshLayout rootLayout = ((PullToRefreshLayout) v.findViewById(R.id.listrefresh_view));
		rootLayout.setOnRefreshListener(new MyListener(){
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout){
				//上拉刷新的页面操作，为了避免频繁访问数据库，上拉不发送内容，数据直接存在mhouselist
				super.onRefresh(rootLayout);
			}
			
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout){
				//上拉加载的页面操作
				if(msqlParam.getMtotalRow() != 0){
					int index = msqlParam.getMselectIndex();//目前查询的标记
					if(index < msqlParam.getMtotalRow()){
						//只要小于总数，就可以再发送命令
						msqlParam.setMselectIndex(index);
						msqlParam.setMselectnum(Common.MAXSQLDATANUM);
						int position = msqlParam.getPosition();
						mHandleSql.SendMsg(msqlParam.getCmd(),position,0,msqlParam);
					}
					super.onLoadMore(rootLayout);
				}
				
			}
		});
		
		houselv = (PullableListView)v.findViewById(R.id.house_listview);
		mhouselist = new ArrayList<houseData>();
		
		madapter = new houseListAdapter(getActivity(), mhouselist);
		houselv.setAdapter(madapter);
		houselv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View arg1, int position,
                    long id) {
            	//列表上的第几项被选中,直接建立一个新的fragment
              Bundle args = new Bundle();  
               houseData itemData = new houseData();
               itemData = mhouselist.get(position);
               args.putSerializable(Common.KEY_HOUSE_ITEM,itemData);
               args.putSerializable(Common.KEY_CITYINFO, mcity);
               Intent i = new Intent(getActivity(),houseitemActivity.class);
			   i.putExtras(args);
			   startActivity(i);
            }
        });
		
		
		ImageButton btnBack = (ImageButton)v.findViewById(R.id.btnBack);
		btnBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				getActivity().finish();
			}
		});
		
		//百度定位地图按钮
		Button btnMap = (Button)v.findViewById(R.id.btnLocation);
		btnMap.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(getActivity(), "搜索功能暂缺", Toast.LENGTH_LONG).show();
				
			}
		});
		
	}

	private void initVaule() {
		
		mViewArray.add(sortArea,viewArea);
		mViewArray.add(sortTotalPrice,viewPrice); 
		mViewArray.add(sortMore,viewMore);
		expandTabView.setValue(mViewArray);
		
		expandTabView.setTitle(viewArea.getShowText(),sortArea);
		expandTabView.setTitle(viewPrice.getShowText(), sortTotalPrice);
		expandTabView.setTitle(viewMore.getShowText(), sortMore);
	
		
	}

	private void initListener() {
		
		viewArea.setOnSelectListener(new ViewArea.OnSelectListener() {

			@Override
			public void getValue(int position, String showText) {
				onRefresh(viewArea,showText);
				selectReply(sortArea,position);
			}
		});
		
		viewPrice.setOnSelectListener(new ViewPrice.OnSelectListener() {

			@Override
			public void getValue(int position, String showText) {
				onRefresh(viewPrice,showText);
				selectReply(sortTotalPrice,position);
			}
		});
		
		viewMore.setOnSelectListener(new ViewMore.OnSelectListener() {
			
			@Override
			public void getValue(int leftPosition,int rightposition,String showText) {
				onRefresh(viewMore,showText);
				selectMoreReply(leftPosition,rightposition);
			}
		});	
	}
	
	private void onRefresh(View view,String showText) {
		
		expandTabView.onPressBack();
		int position = getPositon(view);
		if (position >= 0 && !expandTabView.getTitle(position).equals(showText)) {
			expandTabView.setTitle(showText, position);
		}
	}
	
	
	
	private int getPositon(View tView) {
		for (int i = 0; i < mViewArray.size(); i++) {
			if (mViewArray.get(i) == tView) {
				return i;
			}
		}
		return -1;
	}
	
	public void onBackPressed() {
		
		if (!expandTabView.onPressBack()) {
			getActivity().finish();
		}
		
	}
	
	private void selectReply(int key,int position) {
		switch(key)
		{
			case sortArea:{
				msqlParam.setCmd(Common.MESSAGE_SELECTSQLAREA);
				msqlParam.setMselectIndex(0);
				msqlParam.setMselectnum(Common.MAXSQLDATANUM);
				msqlParam.setPosition(position);
				mHandleSql.SendMsg(Common.MESSAGE_SELECTSQLAREA,position,0,msqlParam);
			}
			break;
			case sortTotalPrice:{
				msqlParam.setCmd(Common.MESSAGE_SELECTTOTALSQLPRICE);
				msqlParam.setMselectIndex(0);
				msqlParam.setMselectnum(Common.MAXSQLDATANUM);
				msqlParam.setPosition(position);
				mHandleSql.SendMsg(Common.MESSAGE_SELECTTOTALSQLPRICE,position,0,msqlParam);
			}
			break;
			default:
				break;	
		}
	}
	
	private void selectMoreReply(int leftposition,int rightposition) {
		MORESELECT moreSel = MORESELECT.values()[leftposition];
		switch(moreSel)
		{
			case SORT: {
				SortMore(rightposition);
			}
			break;
			case HOUSETYPE:{
				selectByhouseType(rightposition);
			}
			break;
			case ZX:{
				selectByZx(rightposition);
			}
			break;
			case PMPRICE:{
				selectByPmPrice(rightposition);
			}
			break;
			default:
				break;
		}
	}
	
	private void SortMore(int rightposition)
	{
		SORTKIND sortKind = SORTKIND.values()[rightposition];
		switch(sortKind)
		{
			case SORTALL: {
			
				return;
			}
			case SORTBYPMPRICEH_L:{
				msqlParam.setCmd(Common.MESSAGE_SORTBYPRICEH_L);
				msqlParam.setMselectIndex(0);
				msqlParam.setMselectnum(Common.MAXSQLDATANUM);
				msqlParam.setPosition(0);
				mHandleSql.SendMsg(Common.MESSAGE_SORTBYPRICEH_L,0,0,msqlParam);
			}
			break;
			case SORTBYPMPRICEL_H:{
				msqlParam.setCmd(Common.MESSAGE_SORTBYPRICEL_H);
				msqlParam.setMselectIndex(0);
				msqlParam.setMselectnum(Common.MAXSQLDATANUM);
				msqlParam.setPosition(0);
				mHandleSql.SendMsg(Common.MESSAGE_SORTBYPRICEL_H,0,0,msqlParam);
			}
			break;
			case SORTBYYEARH_L:{
				msqlParam.setCmd(Common.MESSAGE_SORTBYYEARH_L);
				msqlParam.setMselectIndex(0);
				msqlParam.setMselectnum(Common.MAXSQLDATANUM);
				msqlParam.setPosition(0);
				mHandleSql.SendMsg(Common.MESSAGE_SORTBYYEARH_L,0,0,msqlParam);
			}
			break;
			case SORTBYYEARL_H:{
				msqlParam.setCmd(Common.MESSAGE_SORTBYYEARL_H);
				msqlParam.setMselectIndex(0);
				msqlParam.setMselectnum(Common.MAXSQLDATANUM);
				msqlParam.setPosition(0);
				mHandleSql.SendMsg(Common.MESSAGE_SORTBYYEARL_H,0,0,msqlParam);
			}
			break;
			case SORTBYAREAH_L: {
				msqlParam.setCmd(Common.MESSAGE_SORTBYAREAH_L);
				msqlParam.setMselectIndex(0);
				msqlParam.setMselectnum(Common.MAXSQLDATANUM);
				msqlParam.setPosition(0);
				mHandleSql.SendMsg(Common.MESSAGE_SORTBYAREAH_L,0,0,msqlParam);
			}
			break;
			case SORTBYAREAL_H: {
				msqlParam.setCmd(Common.MESSAGE_SORTBYAREAL_H);
				msqlParam.setMselectIndex(0);
				msqlParam.setMselectnum(Common.MAXSQLDATANUM);
				msqlParam.setPosition(0);
				mHandleSql.SendMsg(Common.MESSAGE_SORTBYAREAL_H,0,0,msqlParam);
			}
			break;
			default:
				break;
		}
			
	}
	
	private void selectByhouseType(int rightposition)
	{
		msqlParam.setCmd(Common.MESSAGE_SELECTBYHOUSETYPE);
		msqlParam.setMselectIndex(0);
		msqlParam.setMselectnum(Common.MAXSQLDATANUM);
		msqlParam.setPosition(rightposition);
		mHandleSql.SendMsg(Common.MESSAGE_SELECTBYHOUSETYPE,rightposition,0,msqlParam);
	}
	
	private void selectByZx(int rightposition){
		msqlParam.setCmd(Common.MESSAGE_SELECTBYZX);
		msqlParam.setMselectIndex(0);
		msqlParam.setMselectnum(Common.MAXSQLDATANUM);
		msqlParam.setPosition(rightposition);
		mHandleSql.SendMsg(Common.MESSAGE_SELECTBYZX,rightposition,0,msqlParam);
	}
	
	private void selectByPmPrice(int rightposition){
		msqlParam.setCmd(Common.MESSAGE_SELECTBYPMPRICE);
		msqlParam.setMselectIndex(0);
		msqlParam.setMselectnum(Common.MAXSQLDATANUM);
		msqlParam.setPosition(rightposition);
		mHandleSql.SendMsg(Common.MESSAGE_SELECTBYPMPRICE,rightposition,0,msqlParam);
	}
	
	
}
